import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

// 报名信息类
class Signup {
    private String studentId, name, clazz, grade, major, college, signupType, eventId;
    public Signup(String studentId, String name, String clazz, String grade, String major, String college,
                  String signupType, String eventId) {
        this.studentId = studentId; this.name = name; this.clazz = clazz; this.grade = grade;
        this.major = major; this.college = college; this.signupType = signupType; this.eventId = eventId;
    }
    @Override
    public String toString() {
        return studentId + "," + name + "," + clazz + "," + grade + "," + major + "," + college + "," +
                signupType + "," + (eventId == null ? "" : eventId);
    }
    public static Signup fromString(String line) {
        String[] parts = line.split(",", -1);
        if (parts.length < 8) return null;
        return new Signup(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
    }
}

// 报名管理器，负责读写文件
class SignupManager {
    private List<Signup> signups = new ArrayList<>();
    private final String filePath = "signups.txt";

    public SignupManager() {
        loadFromFile();
    }
    public void addSignup(Signup signup) {
        signups.add(signup);
        saveToFile(signup);
    }
    public List<Signup> getAllSignups() {
        return signups;
    }
    private void loadFromFile() {
        File file = new File(filePath);
        if (!file.exists()) return;
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                Signup s = Signup.fromString(line);
                if (s != null) signups.add(s);
            }
        } catch (IOException e) { e.printStackTrace(); }
    }
    private void saveToFile(Signup signup) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true))) {
            bw.write(signup.toString());
            bw.newLine();
        } catch (IOException e) { e.printStackTrace(); }
    }
}

public class StudentSignupFrame extends JFrame {
    private JTextField studentIdField = new JTextField(15);
    private JTextField nameField = new JTextField(15);
    private JTextField classField = new JTextField(15);
    private JTextField gradeField = new JTextField(15);
    private JTextField majorField = new JTextField(15);
    private JTextField collegeField = new JTextField(15);
    private JComboBox<String> signupTypeCombo = new JComboBox<>(new String[]{"参赛项目", "志愿者", "裁判员"});
    private JTable projectTable;
    private DefaultTableModel projectTableModel;
    private SignupManager signupManager = new SignupManager();

    public StudentSignupFrame() {
        setTitle("学生报名页面");
        setSize(700, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 窗口居中

        // 粉色背景
        getContentPane().setBackground(new Color(255, 228, 236));

        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(new Color(255, 228, 236));
        mainPanel.setBorder(new EmptyBorder(15, 15, 15, 15));

        // 左侧输入区，用GridBagLayout居中对称布局
        JPanel inputPanel = new JPanel(new GridBagLayout());
        inputPanel.setBackground(new Color(255, 228, 236));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // Helper to add label+field pairs centered
        addLabelField(inputPanel, gbc, 0, "学号:", studentIdField);
        addLabelField(inputPanel, gbc, 1, "姓名:", nameField);
        addLabelField(inputPanel, gbc, 2, "班级:", classField);
        addLabelField(inputPanel, gbc, 3, "年级:", gradeField);
        addLabelField(inputPanel, gbc, 4, "专业:", majorField);
        addLabelField(inputPanel, gbc, 5, "学院:", collegeField);

        // 报名类型
        gbc.gridx = 0; gbc.gridy = 6;
        gbc.gridwidth = 1;
        JLabel signupTypeLabel = new JLabel("报名类型:");
        signupTypeLabel.setHorizontalAlignment(SwingConstants.CENTER);
        signupTypeLabel.setForeground(new Color(120, 0, 60));
        inputPanel.add(signupTypeLabel, gbc);

        gbc.gridx = 1;
        signupTypeCombo.setBackground(new Color(255, 200, 230));
        inputPanel.add(signupTypeCombo, gbc);

        mainPanel.add(inputPanel, BorderLayout.WEST);

        // 右侧项目列表
        projectTableModel = new DefaultTableModel(new Object[]{"项目ID", "项目名称", "时间", "地点"}, 0) {
            public boolean isCellEditable(int row, int column) { return false; }
        };
        projectTable = new JTable(projectTableModel);
        projectTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        projectTable.setBackground(new Color(255, 240, 245));

        // 模拟项目数据（你可以改成从 EventManager 读取）
        projectTableModel.addRow(new Object[]{"E001", "百米跑", "2025-06-01 09:00", "体育场"});
        projectTableModel.addRow(new Object[]{"E002", "跳远", "2025-06-02 10:00", "田径场"});

        JScrollPane projectScroll = new JScrollPane(projectTable);
        projectScroll.setPreferredSize(new Dimension(350, 300));
        mainPanel.add(projectScroll, BorderLayout.CENTER);

        // 报名按钮
        JButton signupBtn = new JButton("提交报名");
        signupBtn.setBackground(new Color(255, 150, 180));
        signupBtn.setForeground(Color.WHITE);
        signupBtn.setFocusPainted(false);

        signupBtn.addActionListener(e -> submitSignup());

        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(new Color(255, 228, 236));
        bottomPanel.add(signupBtn);

        mainPanel.add(bottomPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void addLabelField(JPanel panel, GridBagConstraints gbc, int y, String labelText, JTextField field) {
        gbc.gridx = 0; gbc.gridy = y;
        JLabel label = new JLabel(labelText);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setForeground(new Color(120, 0, 60));
        panel.add(label, gbc);

        gbc.gridx = 1;
        field.setBackground(new Color(255, 240, 245));
        panel.add(field, gbc);
    }

    private void submitSignup() {
        String studentId = studentIdField.getText().trim();
        String name = nameField.getText().trim();
        String clazz = classField.getText().trim();
        String grade = gradeField.getText().trim();
        String major = majorField.getText().trim();
        String college = collegeField.getText().trim();
        String signupType = (String) signupTypeCombo.getSelectedItem();

        if (studentId.isEmpty() || name.isEmpty() || clazz.isEmpty() || grade.isEmpty() ||
                major.isEmpty() || college.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写完整信息！");
            return;
        }

        String eventId = null;
        if (!signupType.equals("志愿者")) { // 参赛项目或裁判员必须选项目
            int selectedRow = projectTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请选择一个项目！");
                return;
            }
            eventId = (String) projectTableModel.getValueAt(selectedRow, 0);
        }

        Signup signup = new Signup(studentId, name, clazz, grade, major, college, signupType, eventId);
        signupManager.addSignup(signup);

        JOptionPane.showMessageDialog(this, "报名成功！");
        clearForm();
    }

    private void clearForm() {
        studentIdField.setText("");
        nameField.setText("");
        classField.setText("");
        gradeField.setText("");
        majorField.setText("");
        collegeField.setText("");
        signupTypeCombo.setSelectedIndex(0);
        projectTable.clearSelection();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            StudentSignupFrame frame = new StudentSignupFrame();
            frame.setVisible(true);
        });
    }
}
